# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

# library(MetaboAnalystR)
library(ggplot2)
library(ggrepel)
library(dplyr)
library(tidyr)
library(tibble)
library(ropls)
library(pROC)
library(egg)
library(purrr)
library(stringr)
library(randomForest)
library(Boruta)
library(magrittr)

options(digits = 3)

sampleInfo <- read.csv("SampleInfo.csv", header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

head(sampleInfo)

diffData <- read.table("diff_table.txt", header = T, sep = "\t", stringsAsFactors = F) %>%
filter(p < 0.05)

nrow(diffData)

data <- read.csv("AllMet1.csv", header = T) %>%
    select(- c(1, 3 : 5)) %>%
    filter(Name %in% diffData$Name) %>%
    gather("SampleID", "Value", - Name) %>%
    spread(Name, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID")) %>%
    column_to_rownames("SampleID") %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
    as.data.frame()

x <- data %>% select(- c("ClassNote"))
y <- data$ClassNote

svmRs <- Boruta(x, y, maxRuns = 100)
decData <- borutaRs$finalDecision %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    set_colnames(c("Metabolite", "decision"))

decData

sortData <- borutaRs$ImpHistory %>%
    t() %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        data <- result[- 1] %>%
            unlist() %>%
            discard(~ is.infinite(.x))
        median <- median(data, na.rm = T)
        result$median <- median
        result
    }) %>%
    arrange(median) %>%
    as.data.frame()

sortData

sortNames <- sortData$Name

imp <- borutaRs$ImpHistory %>%
    t() %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    gather("Sample", "Value", - Name) %>%
    left_join(decData, by = c("Metabolite")) %>%
    mutate_at(vars("decision"), function(x){
        ifelse(is.na(x), "Shadow", as.character(x))
    }) %>%
    filter(decision != "Tentative") %>%
    mutate(Name = factor(Name, levels = sortNames)) %>%
    mutate(decision = factor(decision, levels = c("Shadow", "Rejected", "Confirmed"))) %>%
    as.data.frame()

head(imp)

windowsFonts(Times = windowsFont("Times New Roman"))

p <- ggplot(imp, mapping = aes(x = Name, y = Value, fill = decision)) +
    ylab("Importance") +
    xlab("") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1, vjust = 1), legend.position = 'top',
    legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 8.8),
    axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12),
    panel.border = element_rect(size = 0.75)
    ) +
    geom_boxplot() +
    scale_fill_manual("finalDecision", values = c("#0000FF", "#FF0000", "#00FF00"))

ggsave(limitsize = FALSE,'tmp.pdf', p, width = 10, height = 6)




